let fileMaxSize = 2 * 1024; // 默认最大为2M
let fileMinSize = 50; // 最小为50KB
//APP压缩图片
export function appCompressImg(img) {
	console.log('开始压缩');
	let that = this
	return new Promise((res) => {
		// var localPath = plus.io.convertAbsoluteFileSystem(img);
		plus.io.resolveLocalFileSystemURL(img, (entry) => { //通过URL参数获取目录对象或文件对象
			entry.file((file) => { // 可通过entry对象操作图片 
				console.log('压缩前图片信息:' + JSON.stringify(file)); //压缩前图片信息
				
				if (file.size > 512000) { //   如果大于500Kb进行压缩
					plus.zip.compressImage({ // 5+ plus.zip.compressImage 了解一下，有详细的示例
						src: img, //src: 压缩原始图片的路径    
						dst: img.replace('.png', '2222.png').replace('.PNG',
							'2222.PNG').replace('.jpg', '2222.jpg').replace(
							'.JPG', '2222.JPG'),
						width: '40%', //dst: (String 类型 )压缩转换目标图片的路径，这里先在后面原始名后面加一个2222区分一下
						height: '40%', //width,height: (String 类型 )缩放图片的宽度,高度
						quality: 10, //quality: (Number 类型 )压缩图片的质量
						overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
						// format:'jpg'   //format: (String 类型 )压缩转换后的图片格式
					}, (event) => {
						console.log('压缩后图片信息:' + JSON.stringify(event)); // 压缩后图片信息
						let newImg = event.target;
						res(newImg); //返回新的图片地址，在uploadFile之前接收
					}, function(err) {
						// console.log('Resolve file URL failed: ' + err.message);
					});
				} else { //else小于500kb跳过压缩，直接返回现有的src
					res(img);
				}
			});
		}, (e) => { // 返回错误信息
			// console.log('Resolve file URL failed: ' + e.message);
		});
	})
}


function getCompressionRatio(fileSize) {
	const multiple = (fileSize / fileMaxSize).toFixed(2) // 获取文件大小倍数，生成质量比
	console.log(multiple)
	let compressionRatio = 1
	if (multiple > 5) {
		compressionRatio = 0.5
	} else if (multiple > 4) {
		compressionRatio = 0.6
	} else if (multiple > 3) {
		compressionRatio = 0.7
	} else if (multiple > 2) {
		compressionRatio = 0.8
	} else if (multiple > 1) {
		compressionRatio = 0.9
	} else {
		compressionRatio = 2
	}
	return compressionRatio;
}


// H5图片压缩
/**
 * file 文件信息
 */
export function h5CompressImg(file) {
	return new Promise(resolve => {

		const scale = getCompressionRatio(file.size)
		const fileName = file.name
		if (scale > 1) {
			uni.$u.toast('文件' + fileName + '大于10M')
			return resolve(false)
		}
		const type = file.type
		

		// uni.$u.toast('压缩中')
		var img = new Image();
		img.src = file.url;
		img.onload = function() {
			var that = this;
			var h = (img.height * scale).toFixed(0); // 默认按质量比例压缩
			var w = (img.width * scale).toFixed(0);
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			var width = document.createAttribute("width");
			width.nodeValue = w;
			var height = document.createAttribute("height");
			height.nodeValue = h;
			canvas.setAttributeNode(width);
			canvas.setAttributeNode(height);
			ctx.drawImage(that, 0, 0, w, h);
			var base64 = canvas.toDataURL(type, scale); //压缩比例
			canvas = null;
			let data = {}
			if (type == 'base64') {
				data = {
					size: getBase64Size(base64),
					type: type,
					source: base64
				}
			} else {
				data = base64ToBlob(base64);
				// console.log('压缩后的大小', blob, blob.size, blob.type)
				const blobUrl = window.URL.createObjectURL(data); //blob地址
				data.source = blobUrl
			}
			console.log(data)
			if (data.size < fileMinSize) {
				uni.$u.toast('文件' + fileName + '不能小于50KB')
				return resolve(false)
			}
			resolve(data.source);
		}
	})
}

// base转Blob
export function base64ToBlob(base64) {
	var arr = base64.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}

// 获取base64的文件大小
export function getBase64Size(base64Str) {
	let size = 0;
	if (base64Str) { // 获取base64图片byte大小
		const equalIndex = base64Str.indexOf('='); // 获取=号下标
		if (equalIndex > 0) {
			const str = base64Str.substring(0, equalIndex); // 去除=号
			const strLength = str.length;
			const fileLength = strLength - (strLength / 8) * 2; // 真实的图片byte大小
			size = Math.floor(fileLength); // 向下取整
		} else {
			const strLength = base64Str.length;
			const fileLength = strLength - (strLength / 8) * 2;
			size = Math.floor(fileLength); // 向下取整
		}
	} else {
		size = null;
	}
	return size
}